import React from 'react'
import {connect} from 'react-redux'
import {messages} from "share/common";
import { Alert, Form, Button, Input, InputNumber, Select, Switch, Table, Popover } from 'antd'
import autoAuditService from 'containers/finance-setting/auto-audit/auto-audit.service'
import 'styles/finance-setting/auto-audit/auto-audit-rule.scss'
import ListSelector from 'components/list-selector'
import { message } from 'antd';
import ResizeTable from 'components/resize-table'
const FormItem = Form.Item;
const Search = Input.Search;
const Option = Select.Option;
const formItemLayout = {
  labelCol: {span: 8},
  wrapperCol: {span: 14},
};

class AutoAuditRule extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      setOfBook: [],
      setOfBookId: '',
      columns: [
        {title:messages('finance-setting.key88'/*公司代码*/),dataIndex: 'companyCode', width: '45%', render: value => <Popover content={value} placement={'topLeft'}>{value}</Popover>},
        {title:messages('finance-setting.key89'/*公司名称*/),dataIndex: 'name', width: '30%', render: value => <Popover content={value} placement={'topLeft'}>{value}</Popover>},
        {
          title:messages('common.operation')/*操作*/,dataIndex: 'operate', width: '10%',
          render: (value,record) => {
            return <a onClick={e => this.deleteCompany(e,record)}>{messages('common.delete')/*删除*/}</a>
          }
        }
      ],
      pagination: {
        total: 0,
      },
      page: 0,
      size: 10,
      companyTableLoading: false,
      data: [],
      searchInfo: '',
      filterData: [],
      showAdditionalSelector: false,
      chooseCompanyNumber: 0,
      ruleInfos: {},
      saveLoading: false
    }
  }

  componentWillMount(){
    this.getSetOfBook();
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.showAuditRule === this.props.showAuditRule)
      return;
    if (!nextProps.showAuditRule) {
      this.props.form.resetFields();
      return !1;
    }
    this.props.form.resetFields();
    this.setState({
      data: JSON.parse(JSON.stringify(nextProps.ruleInfo)).companyDTOs || [],
      filterData: nextProps.ruleInfo.companyDTOs,
      setOfBookId: nextProps.ruleInfo.setOfBooksId,
      chooseCompanyNumber: nextProps.ruleInfo.companyDTOs ? nextProps.ruleInfo.companyDTOs.length : 0,
      ruleInfos: nextProps.ruleInfo
    });
  }

  //保存
  handleSave = () => {
    const { data, ruleInfos } = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if(!err){
        this.setState({saveLoading:true});
        let params = JSON.parse(JSON.stringify(ruleInfos));
        params.enabled = values.enabled;
        params.priority = values.priority;
        params.ruleCode = values.ruleCode;
        params.ruleName = values.ruleName;
        params.setOfBooksId = values.setOfBookId;
        let companyItems = [];
        data.length && data.map((item) => {
          let tempItem = {};
          tempItem.companyCode = item.companyCode;
          tempItem.name = item.name;
          tempItem.companyTypeName = item.companyTypeName;
          tempItem.id = item.id;
          companyItems.push(tempItem);
        });
        params.companyDTOs = companyItems;
        //新建或编辑
        if(params.id){
          autoAuditService.upDataAuditRule(params).then(() => {
            this.setState({saveLoading:false});
            this.props.close(true);
          }).catch((e) => {
            this.setState({saveLoading:false});
            message.error(e.response.data.message);
          });
        }else {
          autoAuditService.saveAutoAuditRule(params).then(() => {
            this.props.close(true);
            this.setState({saveLoading:false});
          }).catch((e) => {
            this.setState({saveLoading:false});
            message.error(e.response.data.message);
          });
        }
      }
    });
  };

  //所属帐套
  getSetOfBook = () => {
    autoAuditService.getSetOfBooksByTenant().then(res => {
      this.setState({setOfBook:res.data})
    })
  };

  //帐套更换
  getSetOfBookChange = (value) => {
    this.setState({
      setOfBookId: value,
      data: [],
      filterData: [],
      searchInfo: '',
      chooseCompanyNumber: 0
    })
  };

  //分配公司按钮,选择帐套下的公司
  getBookCompany = () => {
    this.setState({showAdditionalSelector: true})
  };

  //删除公司
  deleteCompany = (e,record) => {
    e.stopPropagation();
    const { data } = this.state;
    data.map((item,index) => {
      item.id === record.id && data.splice(index,1);
    });
    this.setState({data},() => {
      this.handleChangeKey(this.state.searchInfo);
      this.setState({chooseCompanyNumber: this.state.data.length})
    });
  };

  //搜索公司
  handleChangeKey = (e) => {
    let { data, filterData } = this.state;
    let value = e.target ? e.target.value : e;
    this.setState({searchInfo:value},() => {
      if(!value || value === ''){
        this.setState({filterData:data})
      }else {
        filterData = [];
        data.map((item) => {
          (item.companyCode.indexOf(value) > -1 || item.name.indexOf(value) > -1) && filterData.push(item);
        });
        this.setState({filterData});
      }
    });
  };

  //选择分配公司
  handleSelectAddition = (rows) => {
    this.setState({data:rows.result,showAdditionalSelector: false},() => {
      this.setState({chooseCompanyNumber: this.state.data.length});
      this.handleChangeKey(this.state.searchInfo);
    })
  };

  render(){
    const { setOfBook, setOfBookId, columns, pagination, companyTableLoading, data, filterData, showAdditionalSelector, chooseCompanyNumber, saveLoading } = this.state;
    const {getFieldDecorator} = this.props.form;
    const { ruleInfo } = this.props;
    return(
      <div className="auto-audit-rule">
        <div className="auto-rule-content">
          <Alert
            message={messages('common.help')/*帮助提示*/}
            description={<div>{messages('finance-setting.key91'/*同一帐套下允许设置多个自动审核控制规则；*/)}<br/>{messages('finance-setting.key92'/*一个公司允许分配多个规则。*/)}</div>}
            type="info"
            showIcon
          />
          <Form onSubmit={this.handleSave} style={{marginTop:'10px'}}>
            <FormItem className="priority-wrap"
                      label={messages('finance-setting.key71'/*规则编码*/)} {...formItemLayout}>
              {getFieldDecorator('ruleCode', {
                rules: [{
                  required: true, message: messages('common.please.input')/*请输入*/,
                },{
                  max: 50,
                  message: messages('finance-setting.key93'/*规则编码最多不超过50个字符*/)
                }],
                initialValue: ruleInfo.ruleCode ? ruleInfo.ruleCode : ''
              })(
                <Input placeholder={messages('common.please.input')/*请输入*/} disabled={ruleInfo.ruleCode ? true :false}/>
              )}
            </FormItem>
            <FormItem className="priority-wrap"
                      label={messages('finance-setting.key72'/*规则名称*/)} {...formItemLayout}>
              {getFieldDecorator('ruleName', {
                rules: [{
                  required: true, message: messages('common.please.input')/*请输入*/,
                },{
                  max: 50,
                  message: messages('finance-setting.key80'/*规则名称最多不超过50个字符*/)
                }],
                initialValue: ruleInfo.ruleName ? ruleInfo.ruleName : ''
              })(
                <Input placeholder={messages('common.please.input')/*请输入*/}/>
              )}
            </FormItem>
            <FormItem className="priority-wrap"
                      label={messages('finance-setting.key73'/*所属帐套*/)} {...formItemLayout}>
              {getFieldDecorator('setOfBookId', {
                rules: [{
                  required: true, message: messages('common.select')/*请选择*/,
                }],
                initialValue: ruleInfo.setOfBooksId ? ruleInfo.setOfBooksId : ''
              })(
                <Select placeholder={messages('common.select')/*请选择*/} onChange={this.getSetOfBookChange} disabled={ruleInfo.setOfBooksId ? true :false}>
                  {
                    setOfBook.map(item => {
                      return <Option key={item.id} title={item.setOfBooksName}>{item.setOfBooksName}</Option>
                    })
                  }
                </Select>
              )}
            </FormItem>
            <FormItem className="priority-wrap"
                      label={messages('finance-setting.key74'/*优先级*/)} {...formItemLayout}>
              {getFieldDecorator('priority', {
                rules: [{
                  required: true, message: messages('common.please.input')/*请输入*/,
                }],
                initialValue: ruleInfo.priority ? ruleInfo.priority : ''
              })(
                <InputNumber formatter={this.showPriority}
                             disabled={ruleInfo.priority ? true :false}
                             parser={value => value}
                             min={1}/>
              )}
            </FormItem>
            <FormItem className="priority-wrap"
                      label={messages('common.column.status')/*状态*/} {...formItemLayout}>
              {getFieldDecorator('enabled',{
                rules: [{
                  required: true
                }],
                initialValue: typeof ruleInfo.enabled === "boolean" ? ruleInfo.enabled : true,
                valuePropName: 'checked'
              })(
                <Switch/>
              )}
            </FormItem>
          </Form>
          {
            setOfBookId && setOfBookId !== '' &&
            <div>
              <div className="auto-audit-company-title"><span>{messages('finance-setting.key94'/*分配公司*/)}</span></div>
              <div className="auto-audit-company-operate">
                <Button type="primary" onClick={this.getBookCompany} style={{marginRight:'10px'}}>{messages('finance-setting.key94'/*分配公司*/)}</Button> {messages('finance-setting.key95'/*已选择*/)}<span className="auto-audit-company-number">{chooseCompanyNumber}</span>{messages('finance-setting.key96'/*个公司*/)}
                <Search onChange={this.handleChangeKey}
                        style={{display:'block',float:'right',width:'200px'}}
                        placeholder={messages('finance-setting.key97'/*请输入公司代码/名称*/)}/>
              </div>
              <ResizeTable
                columns={columns}
                className={'auto-audit-table'}
                dataSource={filterData}
                bordered
                pagination={pagination}
                scroll={{ y: 240 }}
                loading={companyTableLoading}
              />
            </div>
          }
        </div>
        <div className="footer-operate" style={{backgroundColor:'#ffffff',left:'0px'}}>
          <Button type="primary"  onClick={this.handleSave} style={{margin:'0px 10px'}} loading={saveLoading}>{messages('common.save')/*保存*/}</Button>
          <Button onClick={this.props.close}>{messages('common.cancel')/*取消*/}</Button>
        </div>
        <ListSelector visible={showAdditionalSelector}
                      type="auto_audit_add_company"
                      selectedData={ data }
                      extraParams={{setOfBooksId: setOfBookId, roleType: 'TENANT', enabled: true}}
                      onOk={this.handleSelectAddition}
                      onCancel={() => this.setState({ showAdditionalSelector: false })}/>
      </div>
    )
  }
}

function mapStateToProps(state){
  return {
    tenantInfo: state.login.tenant
  }
}

const wrappedAutoAuditRule = Form.create()(AutoAuditRule);
export default connect(mapStateToProps)(wrappedAutoAuditRule);
